<!--
 * @Author: luojiajun
 * @Email: company.kachun@gmail.com
 * @Date: 2021-06-29 19:26:39
 * @FilePath: /src/views/database/components/DatabaseDirectoryTreeModal.vue
 * @LastEditTime: 2021-07-20 17:40:50
 * @LastEditors: luojiajun
-->
<template>
    <el-dialog title="表字段限制" :visible.sync="dialogVisible" :before-close="handleClose">
        <div class="db-dir-tree-dialog">
            <div class="db-dir-tree-dialog-header">
                <el-input
                    placeholder="输入关键字进行过滤"
                    suffix-icon="el-icon-search"
                    v-model="keyword"
                ></el-input>
            </div>
            <div class="db-dir-tree-dialog-table">
                <div class="db-dir-tree-dialog-table__header flex">
                    <div class="db-dir-tree-dialog-table__header--th">数据库表单目录</div>
                    <div class="db-dir-tree-dialog-table__header--th">
                        <!-- 字段配置 -->
                        <div class="text">启用</div>
                        <div class="text">停用</div>
                    </div>
                </div>
                <el-tree ref="tree" :data="treeData" default-expand-all node-key="id" :filter-node-method="filterNode" class="edit-tree" :empty-text="emptyText" v-loading="loading" :expand-on-click-node="false">
                    <span class="custom-tree-node db-dir-tree-dialog-table__main flex" slot-scope="{ node, data }">
                        <div class="db-dir-tree-dialog-table__main--td">{{ data.dirName }}</div>
                        <div class="db-dir-tree-dialog-table__main--td">
                            <el-radio-group v-model="data.status" v-if="!data.isTable" @change="(value)=>{ filterSelect(data,value,node) }">
                                <el-radio class="item-radio" :label="1">{{''}}</el-radio>
                                <el-radio class="item-radio" :label="0">{{''}}</el-radio>
                            </el-radio-group>
                            <el-radio-group v-model="data.status" v-else-if="data.children && data.children.length > 0" @change="(value)=>{ filterSelect(data,value,node) }">
                                <el-radio class="item-radio" :label="1">全选{{''}}</el-radio>
                                <el-radio class="item-radio" :label="0">全选{{''}}</el-radio>
                            </el-radio-group>
                        </div>
                    </span>
                </el-tree>
            </div>
        </div>

        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm"
                >确 定</el-button
            >
        </span>
    </el-dialog>
</template>

<script>
import mockJson from "@/views/database/components/mock.json"
import { getDataTreeByTableId, editDataFieldStatus } from "@/api/dataManagement/system/info.js";

export default {
    name: "DatabaseDirectoryTreeModal",
    model: {
        prop: "visible",
        event: "change"
    },
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        tableId: {
            type: [String, Number],
            default: 0
        }
    },
    data() {
        return {
            loading: false,
            keyword: "",
            treeData: [],
            Fnode: {},
            mockJson: mockJson
        };
    },
    watch: {
        keyword(value) {
            this.$refs.tree.filter(value);
        },
        currentId(value) {
            if (value && value > 0) {
                this.fetchData()
            }
        }
    },
    computed: {
        dialogVisible: {
            get() {
                return this.visible;
            },
            set(newValue) {
                this.$emit("change", newValue);
            }
        },
        currentId: {
            get() {
                return this.tableId;
            },
            set(value) {
                this.$emit("update:tableId", value);
            }
        },
        emptyText() {
            return this.loading ? '加载中' : '暂无数据'
        }
    },
    methods: {
        handleClose(done) {
            this.currentId = 0
            done()
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.dirName.indexOf(value) !== -1;
        },
        // 过滤筛选
        filterSelect(data, value, node) {
            data.status = value
            if (node && node.parent) {
                this.changeParent(value, node)

            }
            if (data.children && data.children.length > 0) {
                data.children.forEach(item => {
                    this.filterSelect(item, value)
                })
            }
        },
        changeParent(value, node) {
            if (!node.data.isTable) {
                if (node.parent.childNodes.every(item => {
                    return item.data.status == value
                })) {
                    node.parent.data.status = value
                } else {
                    node.parent.data.status = ''
                }
            } else {
                if (node.parent.childNodes.every(item => {
                    // console.log("aaa:", item.data)
                    return item.data.children && item.data.children.length == 0 || item.data.status == value
                })) {
                    node.parent.data.status = value
                } else {
                    node.parent.data.status = ''
                }
            }

            if (node.parent.parent) {
                this.changeParent(value, node.parent)
            }
        },
        fetchData() {
            if (this.loading) return

            this.loading = true

            getDataTreeByTableId({ tableId: this.currentId })
                .then(res => {
                    if (res.code == 200) {
                        let params = JSON.parse(JSON.stringify(res.data.children))
                        let treeData = params
                        this.Fnode = Object.assign({}, {}, res.data)
                        delete this.Fnode.children
                        
                        this.treeData = this.formatTreeData(treeData)
                    }
                    this.loading = false;
                })
                .catch(() => {
                    this.loading = false;
                });
        },
        formatTreeData(treeData) {
            treeData.forEach((item, i) => {
                item.data.status = item.isTable ? '' : Number(item.data.status[0])
                item = Object.assign({}, item, item.data)
                treeData[i] = item
                if (item.children.length > 0) {
                    // 判断是否需要选择数据表全选按钮
                    if (item.isTable) {
                        let enableNum = 0;
                        let disableNum = 0;
                        item.children.forEach(element => {
                            if (element.data.status == 1) enableNum++
                            if (element.data.status == 2) disableNum++
                        });
                        if (enableNum == item.children.length) item.data.status = 1
                        if (disableNum == item.children.length) item.data.status = 0
                        item = Object.assign({}, item, item.data)
                        treeData[i] = item
                    }
                    return this.formatTreeData(item.children)
                }
            });
            return treeData;
        },
        formatSubmitTreeData(treeData) {
            treeData.forEach((item, i) => {
                item.data = Object.assign({}, item.data, { status: [item.status.toString()] })

                item = Object.assign({}, item, item.data)
                treeData[i] = item
                if (item.children.length > 0) {
                    return this.formatSubmitTreeData(item.children)
                }
            });
            return treeData;
        },
        submitForm() {
            let treeData = JSON.parse(JSON.stringify(this.treeData))
            let tree = { ...this.Fnode, children: this.formatSubmitTreeData(treeData) }

            editDataFieldStatus(tree).then(res => {
                this.$message.success('更新成功');
                this.dialogVisible = false
                this.$emit('close', true)
            }).catch(() => {
                this.$message.error('更新失败');
            })
            
        }
    }
};
</script>

<style lang="scss" scoped>
.db-dir-tree-dialog {
    &-header {
        margin-bottom: 16px;
    }

    &-table {
        border:1px solid #e6e6e6;
        
        .flex {
            flex: 1;
            display: flex;
			align-items: center;
			justify-content: space-between;
        }

		&__header {
			background: #f5f6fa;
			border-bottom: 1px solid #e6e6e6;
            
			&--th {
                padding: 0 10px;
				line-height: 42px;
				color: #1e1e1e;
				font-size: 14px;
                font-weight: 500;
                display: flex;
                align-items: center;

                &:not(:first-child) {
                    width: 200px;
                    border-left: 1px solid #e6e6e6;
                    justify-content: center;
                }

                &:first-child {
                    flex: 1;
                }

                .text {
                    width: 100px;
                    text-align: center;

                    &:last-child {
                        border-left: 1px solid #e6e6e6;
                    }
                }
			}
		}

        &__main {
            &--td {
                padding: 0 10px;
				line-height: 42px;
				font-size: 14px;
                display: flex;
                align-items: center;

                &:not(:first-child) {
                    width: 200px;
                    justify-content: center;
                }
                
                &:first-child {
                    flex: 1;
                }

                .item-radio {
                    width: 100px;
                    margin: 0;
                    text-align: center;
                }
			}
        }

		::v-deep.el-tree-node__content {
			margin: 4px 0px;
		}
	}

	::v-deep.el-radio {
        .el-radio__inner {
            border-radius: 0;
        }
        .el-radio__input.is-checked {
            .el-radio__inner {
                &::after {
                    content: "";
                    position: absolute;
                    left: 2px;
                    top: 3px;
                    width: 9px;
                    height: 5px;
                    border: 2px solid #fff;
                    border-radius: 1px;
                    border-top: none;
                    border-right: none;
                    background: transparent;
                    transform: rotate(-45deg);
                }
            }
        }	
	}

	.edit-tree {
		padding: 4px 0 10px;
	}

	::v-deep.el-form-item {
		padding-right: 10px;
	}
}
</style>
